﻿<template>
  <XenPageLayout title="访客预约" title-align="left">
    <view class="activityForm">
      <uni-forms
        ref="form"
        :modelValue="formData"
        :rules="rules"
        label-width="150px"
        label-position="top"
        validate-trigger="blur"
      >
        <uni-forms-item name="name" label="姓名" :required="true">
          <uni-easyinput
            v-model="formData.name"
            placeholder="请输入访客姓名"
            @blur="validateField('name')"
          />
        </uni-forms-item>

        <uni-forms-item name="phone" label="手机号" :required="true">
          <uni-easyinput
            v-model="formData.phone"
            placeholder="请输入手机号"
            type="number"
            :maxlength="11"
            @blur="validateField('phone')"
          />
        </uni-forms-item>

        <uni-forms-item name="scheduledTime" label="预约时间" :required="true">
          <uni-datetime-picker
            type="datetime"
            v-model="formData.scheduledTime"
            @change="onTimeChange"
          />
        </uni-forms-item>

        <uni-forms-item name="idCard" label="身份证号" :required="true">
          <uni-easyinput
            v-model="formData.idCard"
            placeholder="请输入身份证号码"
            :maxlength="18"
            @blur="validateField('idCard')"
          />
        </uni-forms-item>

        <uni-forms-item
          name="idCardPhotoFront"
          label="身份证正面照片"
          :required="true"
        >
          <view class="id-card-upload">
            <uni-file-picker
              v-model="imageValue"
              fileMediatype="image"
              mode="grid"
              limit="1"
              title="请上传身份证人像面照片"
              :imageStyles="imageStyles"
              :delIcon="true"
              @select="selectFile"
              @success="uploadSuccess"
              @fail="uploadFail"
            ></uni-file-picker>
            <view class="upload-tips">
              <text>1. 请确保照片清晰完整，无反光、遮挡</text>
              <text>2. 身份证信息需真实有效</text>
            </view>
          </view>
        </uni-forms-item>

        <uni-forms-item name="receiverName" label="接待人" :required="true">
          <uni-easyinput
            v-model="formData.receiverName"
            placeholder="请输入接待人"
          />
        </uni-forms-item>

        <uni-forms-item
          name="receiverPhone"
          label="接待人电话"
          :required="true"
        >
          <uni-easyinput
            v-model="formData.receiverPhone"
            placeholder="请输入接待人电话"
            type="number"
            :maxlength="11"
          />
        </uni-forms-item>

        <uni-forms-item name="GroupId" label="被访部门" :required="true">
          <uni-data-select
            v-model="formData.GroupId"
            :localdata="departmentList"
            placeholder="请选择被访部门"
            :clear="false"
            @change="onDepartmentChange"
          ></uni-data-select>
        </uni-forms-item>

        <!-- 完全移除单据编号的展示 -->

        <uni-forms-item name="company" label="所属单位/公司" :required="true">
          <uni-easyinput
            v-model="formData.company"
            placeholder="请输入所属单位/公司"
            @blur="validateField('company')"
          />
        </uni-forms-item>

        <uni-forms-item name="plateNumber" label="车牌号">
          <uni-easyinput
            v-model="formData.plateNumber"
            placeholder="请输入车牌号"
          />
        </uni-forms-item>

        <uni-forms-item name="remark" label="备注信息">
          <uni-easyinput
            v-model="formData.remark"
            placeholder="请输入备注信息"
            type="textarea"
          />
        </uni-forms-item>

        <view class="form-button">
          <button class="submit-button" @click="submitForm">提交</button>
        </view>
      </uni-forms>
    </view>
  </XenPageLayout>
</template>

<script lang="ts" setup>
import XenPageLayout from "@/layouts/XenPageLayout.vue";
import { reactive, ref, onMounted } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import SysVisitorReasonApi from "./api";
import { uploadImage } from "../../../utils/unirequest";
import type { IAddParams, ISysGroupsResponse } from "./api/interface";

// 表单校验规则 - 移除BillCode的校验
const rules = {
  name: {
    rules: [{ required: true, errorMessage: "请输入姓名" }],
  },
  phone: {
    rules: [
      { required: true, errorMessage: "请输入手机号" },
      { pattern: /^1\d{10}$/, errorMessage: "手机号格式不正确" },
    ],
  },
  idCard: {
    rules: [
      { required: true, errorMessage: "请输入身份证号码" },
      {
        pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
        errorMessage: "身份证号码格式不正确",
      },
    ],
  },
  scheduledTime: {
    rules: [
      { required: true, errorMessage: "请选择预约时间" },
      {
        validateFunction: (rule: any, value: any, data: any, callback: any) => {
          const now = new Date().getTime();
          const selectedTime = new Date(value).getTime();

          if (selectedTime <= now) {
            callback("预约时间必须晚于当前时间");
          } else {
            callback();
          }
        },
      },
    ],
  },
  idCardPhotoFront: {
    rules: [{ required: true, errorMessage: "请上传身份证正面照片" }],
  },
  receiverName: {
    rules: [{ required: true, errorMessage: "请输入接待人" }],
  },
  receiverPhone: {
    rules: [
      { required: true, errorMessage: "请输入接待人电话" },
      { pattern: /^1\d{10}$/, errorMessage: "手机号格式不正确" },
    ],
  },
  GroupId: {
    rules: [{ required: true, errorMessage: "请选择所属部门" }],
  },
  company: {
    rules: [{ required: true, errorMessage: "请输入所属单位/公司" }],
  },
};

const form = ref();
const imageValue = ref<any[]>([]);
const departmentList = ref<{ value: string; text: string }[]>([]);

const formData = reactive({
  name: "",
  phone: "",
  idCard: "",
  scheduledTime: "",
  idCardPhotoFront: "",
  receiverName: "",
  receiverPhone: "",
  GroupId: "",
  BillCode: "", // 后台自动获取，用户不可见
  company: "",
  plateNumber: "",
  remark: "",
  reasonId: "",
  wxOpenid: "",
});

// 图片样式
const imageStyles = {
  width: 220,
  height: 140,
  border: {
    radius: "5px",
    width: "1px",
    style: "dashed",
    color: "#DDDDDD",
  },
};

// 获取单据编码
const loadBillCode = async () => {
  try {
    const response = await SysVisitorReasonApi().getCode();

    // 根据接口返回的Data设置单据编码
    if (response && response.Data) {
      formData.BillCode = response.Data;
    } else {
      throw new Error("获取单据编码失败：返回数据为空");
    }
  } catch (error) {
    console.error("获取单据编码失败:", error);
    uni.showToast({
      title: "获取单据编码失败",
      icon: "none",
    });
    // 设置一个默认值或者重试机制
    formData.BillCode = "";
  }
};

// 获取部门列表
const loadDepartmentList = async () => {
  try {
    const response = await SysVisitorReasonApi().getSysGroups();

    departmentList.value = response.map((item: ISysGroupsResponse) => ({
      value: item.Value,
      text: item.Text,
    }));
  } catch (error) {
    console.error("获取部门列表失败:", error);
    uni.showToast({
      title: "获取部门列表失败",
      icon: "none",
    });
  }
};

// 从URL参数获取事由ID，从本地存储获取wxOpenid
onLoad((options) => {
  if (options && options.reasonId) {
    formData.reasonId = options.reasonId;
  }
  formData.wxOpenid = uni.getStorageSync("wxOpenid");
});

// 页面挂载时加载部门列表和单据编码
onMounted(async () => {
  // 并行加载部门列表和单据编码
  await Promise.all([loadDepartmentList(), loadBillCode()]);
});

// 部门选择变化处理
const onDepartmentChange = (value: any) => {
  formData.GroupId = value;
  // 如果有值就清除验证错误
  if (form.value && value) {
    form.value.clearValidate("GroupId");
  }
};

// 文件选择事件 - 使用uploadImage上传
const selectFile = async (e: any) => {
  const filePath = e.tempFiles[0].path || e.tempFiles[0].tempFilePath;
  if (filePath) {
    try {
      // 使用uploadImage方法上传图片
      const imageId = await uploadImage(filePath);

      formData.idCardPhotoFront = imageId;
    } catch (error) {
      console.error("图片上传失败:", error);
      uni.showToast({
        title: "图片上传失败，请重试",
        icon: "none",
      });
    }
  }
};

// 上传成功回调
const uploadSuccess = (e: any) => {};

// 上传失败回调
const uploadFail = (e: any) => {
  uni.showToast({
    title: "身份证照片上传失败，请重试",
    icon: "none",
  });
};

// 提交表单
const submitForm = async () => {
  // 检查reasonId是否已获取
  if (!formData.reasonId) {
    uni.showToast({
      title: "未获取到事由信息，请返回重新选择",
      icon: "none",
    });
    return;
  }

  // 检查单据编码是否已获取
  if (!formData.BillCode) {
    uni.showToast({
      title: "系统正在获取单据编码，请稍后再试",
      icon: "none",
    });
    // 尝试重新获取单据编码
    await loadBillCode();
    if (!formData.BillCode) {
      return;
    }
  }

  await form.value.validate();

  // 构造接口参数
  const apiParams: IAddParams = {
    Entity: {
      Name: formData.name,
      Phone: formData.phone,
      IdCardNo: formData.idCard,
      ReservationTime: formData.scheduledTime,
      IdCardFrontPhotoId: formData.idCardPhotoFront,
      Receptionist: formData.receiverName,
      ReceptionistPhone: formData.receiverPhone,
      Company: formData.company,
      CarNo: formData.plateNumber,
      Remark: formData.remark,
      VisitorReasonId: formData.reasonId,
      GroupId: formData.GroupId,
      BillCode: formData.BillCode, // 自动获取的单据编码
      WorkflowStatus: "提交中",
    },
  };

  // 调用接口提交数据
  const responseData = await SysVisitorReasonApi().add(apiParams);

  uni.showToast({
    title: "提交成功",
    icon: "success",
  });

  // 提交成功后跳转到详情页
  setTimeout(() => {
    uni.redirectTo({
      url: `/subpkg-visitor/visitor/sysvisitorrecordrequestbill/details?id=${responseData.ID}`,
    });
  }, 1000);
};

// 单字段校验方法
const validateField = (fieldName: string) => {
  if (form.value) {
    form.value.validateField(fieldName);
  }
};

// 时间选择处理函数
const onTimeChange = (value: any) => {
  formData.scheduledTime = value;
  setTimeout(() => {
    validateField("scheduledTime");
  }, 100);
};
</script>

<style lang="scss" scoped>
.activityForm {
  padding: 40rpx;
  min-height: 100vh;
  background-color: #f7f8fa;
  padding: 20px;

  &-title {
    font-size: 36rpx;
    font-weight: bold;
    text-align: center;
    margin-bottom: 30rpx;
  }

  .id-card-upload {
    .upload-tips {
      margin-top: 16rpx;
      display: flex;
      flex-direction: column;

      text {
        font-size: 24rpx;
        color: #999;
        line-height: 1.5;
      }
    }
  }

  .form-button {
    margin-top: 50rpx;

    .submit-button {
      color: #fff;
      width: 90%;
      background-color: #b88e67;
      box-shadow: 0 4px 12px rgba(184, 142, 103, 0.2);
      border-radius: 50rpx;
    }
  }

  :deep(.uni-file-picker__container) {
    display: flex;
    flex-direction: column;
  }

  :deep(.file-picker__box-content) {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
